<?php
class Server
{
    private $serv;
    private $client;
    private $cmpp_client;
    private $sgip_client;
    private $smgp_client;
    private $redis_client=null;

    public function __construct()
    {
        $this->serv = new swoole_server("127.0.0.1", 9501);
        $this->serv->set(array(
            'worker_num' => 1,   //一般设置为服务器CPU数的1-4倍
            'daemonize' => 1,  //以守护进程执行
            'max_request' => 3000,
            'task_max_request'=>3000,
            'dispatch_mode' => 2,
            'task_worker_num' => 9,  //task进程的数量 流量 = （ worker_num + task_worker_num) * 100/10
            "task_ipc_mode " => 3,  //使用消息队列通信，并设置为争抢模式
        ));

        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('workerstart', array($this, 'onWorkerStart'));
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }

    public function onReceive($serv, $fd, $from_id, $data)
    {
        $serv->task($data);
    }

    public function onWorkerStart($serv, $worker_id)
    {
        //移动
        $this->cmpp_client = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
        if (!$this->cmpp_client->connect("127.0.0.1", 9502, 1)) {
            return false;
        }

        //联通
        $this->sgip_client = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
        if (!$this->sgip_client->connect("127.0.0.1", 9503, 1)) {
            return false;
        }

        //电信
        $this->smgp_client = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
        if (!$this->smgp_client->connect("127.0.0.1", 9504, 1)) {
            return false;
        }

        // 本服务
        $this->client = new \swoole_client(SWOOLE_SOCK_TCP | SWOOLE_KEEP);
        if (!$this->client->connect("127.0.0.1", 9501, 1)) {
            echo "Connect Error";
            return false;
        }

        $serv->tick(100, function ($id){
            $res = $this->client->send('begin');
        });

        //一分钟发一次心跳，长时间没有数据传输系统会关闭连接
        $serv->tick(60000, function ($id){
            $res = $this->cmpp_client->send('ping');
            $res = $this->sgip_client->send('ping');
            $res = $this->smgp_client->send('ping');
        });
    }

    public function onTask($serv, $task_id, $from_id, $data)
    {
        $redis = $this->redis_conn();
        if($data == 'begin'){
            $data = $redis->lpop("code-swoole-task");
        }
        $array = json_decode($data, true);
        if(!$array){
            return;
        }
        if ($array['mobile'] && $array['content']) {

            if($this->isChinaMobile($array['mobile'])){ //移动
               $res = $this->cmpp_client->send($data);
            }elseif ($this->isChinaUnion($array['mobile'])) { //联通
                $res = $this->sgip_client->send($data);
            }elseif ($this->isChinaTelcom($array['mobile'])) { //电信
                $res = $this->smgp_client->send($data);
            }else{
                $res = $this->cmpp_client->send($data);
            }

            if(!$res){
                $res = $redis->lpush('code-swoole-task',$data);
                return;
            }else{

                $key = 'code_monitor_'.$array['send_list_id'];
                $redis->set($key, 1, 3600*24);
            }
            return $res;
        }
    }

    public function onFinish($serv, $task_id, $data)
    {

    }

    /**
     * 获得redis连接
     * @return bool|null|Redis
     */
    private function redis_conn()
    {
        if (!$this->redis_client) {
            try {
                $this->redis_client = new Redis();
                if (!$this->redis_client->pconnect('127.0.0.1', '6379')) {
                    return false;
                }
                if (!$this->redis_client->auth('123456')) {
                    return false;
                }

            } catch (\Exception $e) {
                return false;
            }
        }
        return $this->redis_client;
    }

    /**
     * 通过正则表达式判断手机号是否是移动号码
     * @param $mobile
     * @return bool
     */
    public function isChinaMobile($mobile)
    {
        if (!$mobile || (strlen($mobile) != 11)) {
            return false;
        }
        $preg_str = '/^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$|^1705\d{7}$/';
        if(preg_match($preg_str,$mobile)){
            return true;
        }
        return false;
    }

    /**
     * 通过正则表达式判断手机号是否是联通号码
     * @param $mobile
     * @return bool
     */
    public function isChinaUnion($mobile)
    {
        if (!$mobile || (strlen($mobile) != 11)) {
            return false;
        }
        $preg_str = '/^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$|^1709\d{7}$/';
        if(preg_match($preg_str,$mobile)){
            return true;
        }
        return false;
    }

    /**
     * 通过正则表达式判断手机号是否是电信号码
     * @param $mobile
     * @return bool
     */
    public function isChinaTelcom($mobile)
    {
        if (!$mobile || (strlen($mobile) != 11)) {
            return false;
        }
        $preg_str = '/^(?:133|153|177|18[019])\d{8}$|^1700\d{7}$|^1349\d{7}$/';
        if(preg_match($preg_str,$mobile)){
            return true;
        }
        return false;
    }
}
$server = new Server();
